﻿using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;

namespace jQuery.Validation.DataAnnotations
{
    public class RequiredValidator : DataAnnotationsModelValidator<RequiredAttribute>
    {
        string _message = "This field is required.";

        public RequiredValidator(ModelMetadata metadata, ControllerContext context, RequiredAttribute attribute)
            : base(metadata, context, attribute)
        {
            if (attribute.ErrorMessage == null)
                attribute.ErrorMessage = _message;
            else
                _message = attribute.ErrorMessage;
        }

        public override IEnumerable<ModelClientValidationRule>GetClientValidationRules()
        {
            var rule = new ModelClientValidationRule
            {
                ErrorMessage = _message,
                ValidationType = "jqv.required"
            };

            rule.ValidationParameters.Add("jQueryName", "required");
            rule.ValidationParameters.Add("jQueryValidationInit", "required: true");

            return new[] { rule };
        }
    }
}
